#include "ScriptSystem.hpp"
#include "Engine.hpp"

ScriptSystem::ScriptSystem(Engine* engine) : m_engine(engine) {

}
    
void ScriptSystem::Update(float deltaTime) {
    auto view = m_engine->getRegistry().view<ScriptComponent>();
    for (auto entity : view) {
        auto& scriptComp = view.get<ScriptComponent>(entity);
        if (scriptComp.instance) {
            scriptComp.instance->OnUpdate(deltaTime);
        }
    }
}

void ScriptSystem::Start() {
    auto view = m_engine->getRegistry().view<ScriptComponent>();
    for (auto entity : view) {
        auto& scriptComp = view.get<ScriptComponent>(entity);
        if (scriptComp.instance) {
            // 设置属性变更回调
            scriptComp.instance->SetPropertyChangedCallback([this, entity](const std::string& name, const PropertyValue& value) {
                // 当属性变更时，更新脚本组件中的属性值
                if (m_engine->getRegistry().all_of<ScriptComponent>(entity)) {
                    auto& comp = m_engine->getRegistry().get<ScriptComponent>(entity);
                    comp.properties[name] = value;
                }
            });
            
            scriptComp.instance->OnStart();
        }
    }
}

void ScriptSystem::Create() {
    auto view = m_engine->getRegistry().view<ScriptComponent>();
    for (auto entity : view) {
        auto& scriptComp = view.get<ScriptComponent>(entity);
        if (scriptComp.instance) {
            scriptComp.instance->OnCreate();
        }
    }
}

void ScriptSystem::Destroy() {
    auto view = m_engine->getRegistry().view<ScriptComponent>();
    for (auto entity : view) {
        auto& scriptComp = view.get<ScriptComponent>(entity);
        if (scriptComp.instance) {
            scriptComp.instance->OnDestroy();
        }
    }
}